import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

// 二级路由
import Layout from '@/views/layout'
import Home from '@/views/layout/home.vue'
import Category from '@/views/layout/category.vue'
import Cart from '@/views/layout/cart.vue'
import User from '@/views/layout/user.vue'
// 一级路由
const Login = () => import('@/views/login')
const Myorder = () => import('@/views/myorder')
const Pay = () => import('@/views/pay')
const Prodetail = () => import('@/views/prodetail')
const Searchlist = () => import('@/views/search/list.vue')
const Search = () => import('@/views/search/index.vue')
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      redirect: '/home',
      component: Layout,
      children: [
        { path: '/home', component: Home },
        { path: '/category', component: Category },
        { path: '/cart', component: Cart },
        { path: '/user', component: User }
      ]
    },
    { path: '/myorder', component: Myorder },
    { path: '/pay', component: Pay },
    { path: '/prodetail/:id', component: Prodetail },
    // 动态路由传参，确认哪个商品列表，路由参数中要携带id
    { path: '/searchlist', component: Searchlist },
    { path: '/search', component: Search }
  ]
  // mode  设置路由模式
})

// 所以路由在真正被解析渲染对应的组件面前，都会先经过全局前置守卫
// 全局前置导航守卫
// to  到哪去  到哪去的完整的路由信息对象（路径，参数）
// from 哪来   从哪来的完整的路由信息对象（路径，参数）
// next()  是否放行
//    (1)next()  直接放行 放行到to里
//    (2)next(路径) 拦截到路径里

// 定义一个数组，专门用户存放所以需要的权限
const authUrls = ['/pay', '/myorder']
router.beforeEach((to, from, next) => {
  // 看to.path是否在authUrls中出现过
  if (!authUrls.includes(to.path)) {
    // 非权限页面放行
    next()
    return
  }
  // 是权限页面,判断权限
  const token = store.getters.token
  // console.log(token)
  if (token) {
    next()
  } else {
    next('/login')
  }
})

// const authUrl = ['/pay', '/myorder']
// router.beforeEach((to, from, next) => {
//   const token = store.getters.token
//   if (!authUrl.includes(to.path)) {
//     next()
//     return
//   }

//   if (token) {
//     next()
//   } else {
//     next('/login')
//   }
// })
export default router
